<template>
    <div class="create-component-list">
        <div
            v-for="(item, index) in list"
            :key="index"
            class="component-item"
            @click="onItemClick(item)"
        >
            <g-text v-bind="item"></g-text>
        </div>
    </div>
    <StyledUploader @success="onImageUploaded"></StyledUploader>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { v4 as uuidv4 } from 'uuid';
import { message } from 'ant-design-vue';
import StyledUploader from '../components/StyledUploader.vue';
import { UploadResp,  } from '../extraType';
import { imageDefaultProps, TextComponentProps } from 'xigua-componentss';
import { ComponentData } from '../store/editor';
import { getImageDimensions } from '@/helper';

export default defineComponent({
    name: 'components-list',
    props: {
        list: {
            type: Array,
            required: true,
        },
    },
    components: {
        StyledUploader,
    },
    emits: ['on-item-click'],
    setup(props, context) {
        const onItemClick = (props: TextComponentProps) => {
            const componentData: ComponentData = {
                name: 'g-text',
                id: uuidv4(),
                props,
            };
            context.emit('on-item-click', componentData)
        };
        const onImageUploaded = (data: { resp: UploadResp; file: File }) => {
            const { resp, file } = data;
            const componentData: ComponentData = {
                name: 'g-image',
                id: uuidv4(),
                props: {
                    ...imageDefaultProps,
                },
            };
            message.success('上传成功');
            componentData.props.src = resp.data.url;
            getImageDimensions(file).then(({ width }) => {
                const maxWidth = 373;
                componentData.props.width = Math.min(width, maxWidth) + 'px';
                context.emit('on-item-click', componentData);
            });
        };
        return {
            onItemClick,
            onImageUploaded,
        };
    },
});
</script>
<style>
/* .create-component-list {
  margin: 0 auto;
} */
.component-item {
    width: 100px;
    margin: 0 auto;
    margin-bottom: 15px;
}
.component-item > * {
  position: static !important;
}
</style>
